package util;

import android.app.ActionBar;
import android.app.Activity;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bigchun.woodhunter.R;
import com.bigchun.woodhunter.databinding.ItemShaixuanallV2Binding;
import com.bigchun.woodhunter.databinding.ItemShaixuangridV2Binding;
import com.bigchun.woodhunter.databinding.ItemShuaixuanitemBinding;
import com.bigchun.woodhunter.databinding.PopupAllshaixuanV2Binding;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import bean.ShaixuanallBean;
import fragment.GoodsFragment;
import myview.InputCustomDialog;

public class FilterPopupUtils {

    private static final ArrayList<Integer> IDS = new ArrayList<>(Arrays.asList(81, 50, 54, 51));


    private final PopupWindow mPopupWindow;
    private final PopupAllshaixuanV2Binding viewBinding;
    private final List<ShaixuanallBean.DataBean> totalData = new ArrayList<>();
    private final Activity activity;
    private final DataAdapter adapter = new DataAdapter();

    public FilterPopupUtils(Activity activity, GoodsFragment fragment) {
        this.activity = activity;
        viewBinding = PopupAllshaixuanV2Binding.inflate(activity.getLayoutInflater());
        View popupWindow = viewBinding.getRoot();
        mPopupWindow = new PopupWindow(popupWindow, ActionBar.LayoutParams.FILL_PARENT,
                ActionBar.LayoutParams.FILL_PARENT);
        // 需要设置一下此参数，点击外边可消失
        mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        mPopupWindow.setOutsideTouchable(true);
        mPopupWindow.setTouchable(true);
        mPopupWindow.setFocusable(true); // pop 显示时， 不让外部 view 响应点击事件
        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        };
        viewBinding.viewZhezhao.setOnClickListener(listener);
        viewBinding.imgBackPop.setOnClickListener(listener);
        viewBinding.recyclerView.setAdapter(adapter);
        viewBinding.tvClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for (int i = 0; i < totalData.size(); i++) {
                    ShaixuanallBean.DataBean dataBean = totalData.get(i);
                    dataBean.getSelected().clear();
                    for (int j = 0; j < dataBean.getAttr_list().size(); j++) {
                        ShaixuanallBean.DataBean.AttrListBean attrListBean = dataBean.getAttr_list().get(j);
                        attrListBean.getSelected().clear();
                        attrListBean.setExpand(false);
                    }
                }
                adapter.notifyDataSetChanged();
            }
        });
        viewBinding.tvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    JSONObject jsonObject = new JSONObject();
                    for (int i = 0; i < totalData.size(); i++) {
                        ShaixuanallBean.DataBean dataBean = totalData.get(i);
                        List<ShaixuanallBean.DataBean.AttrListBean> sel = dataBean.getSelected();
                        StringBuilder stringBuilder = new StringBuilder();
                        for (int j = 0; j < sel.size(); j++) {
                            stringBuilder.append(sel.get(j).getId());
                            stringBuilder.append(",");
                            List<ShaixuanallBean.DataBean.AttrListBean.AttrList2Bean> selected = sel.get(j).getSelected();
                            List<ShaixuanallBean.DataBean.AttrListBean.AttrList2Bean> child = sel.get(j).getAttr_list2();
                            //就是点击大分类的时候筛选展示这整个大分类的产品
                            //点击选中小分类的时候只筛选展示这个小分类的产品
                            if (selected == null || selected.isEmpty()) {
                                for (int k = 0; k < child.size(); k++) {
                                    stringBuilder.append(child.get(k).getId());
                                    stringBuilder.append(",");
                                }
                            } else {
                                for (int k = 0; k < selected.size(); k++) {
                                    stringBuilder.append(selected.get(k).getId());
                                    stringBuilder.append(",");
                                }
                            }

                        }
                        if (dataBean.getCustom() != null) {
                            if (!TextUtils.isEmpty(dataBean.getCustom().value)) {
                                jsonObject.put(getKey(dataBean.getId()), dataBean.getCustom().value);
                            }
                        }
                        if (stringBuilder.length() > 0) {
                            jsonObject.put(dataBean.getId() + "", stringBuilder.substring(0, stringBuilder.length() - 1));
                        }
                    }
                    Log.i("TAG", jsonObject.toString());
                    String data = "";
                    if (jsonObject.length() > 0) {
                        data = jsonObject.toString();
                    }
                    fragment.lastJson = data;
                    fragment.customProgressDialog.show();
                    fragment.getShaixuanResultData(data);
                    dismiss();

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });
    }

    private String getKey(int id) {
        switch (id) {
            case 81:
                return "zhijing";
            case 50:
                return "length";
            case 54:
                return "width";
            case 51:
            default:
                return "gaodu";
        }
    }

    public void dismiss() {
        mPopupWindow.dismiss();
    }

    public void show(View anchor) {
        WindowManager manager = activity.getWindowManager();
        DisplayMetrics dm = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(dm);
        //以要素为单位
        int heightPixels = dm.heightPixels;
        if (Build.VERSION.SDK_INT >= 24) { // Android 7.x中,PopupWindow高度为match_parent时,会出现兼容性问题,需要处理兼容性
            int offsetY = DensityUtil.dip2px(activity, 24);
            if (Build.VERSION.SDK_INT >= 25) { // Android 7.1中，PopupWindow高度为 match_parent 时，会占据整个屏幕
                //故而需要在 Android 7.1上再做特殊处理
                int screenHeight = heightPixels; // 获取屏幕高度
//                int screenHeight = DisplayUtil.getScreenHeight(MainActivity.this); // 获取屏幕高度
                mPopupWindow.setHeight(screenHeight - offsetY); // 重新设置 PopupWindow 的高度
            }
            mPopupWindow.showAtLocation(anchor, Gravity.NO_GRAVITY, 0, offsetY);
        } else {
//            mPopupWindow.showAsDropDown(rl_top);
            int offsetY = DensityUtil.dip2px(activity, 24);
//            if (Build.VERSION.SDK_INT >= 25) { // Android 7.1中，PopupWindow高度为 match_parent 时，会占据整个屏幕
            //故而需要在 Android 7.1上再做特殊处理
            int screenHeight = heightPixels; // 获取屏幕高度
//                int screenHeight = DisplayUtil.getScreenHeight(MainActivity.this); // 获取屏幕高度
            mPopupWindow.setHeight(screenHeight - offsetY); // 重新设置 PopupWindow 的高度
//            }
            mPopupWindow.showAtLocation(anchor, Gravity.NO_GRAVITY, 0, offsetY);
        }
    }

    public void setData(List<ShaixuanallBean.DataBean> list) {
//        rl_top
        this.totalData.clear();
        this.totalData.addAll(list);
        adapter.notifyDataSetChanged();

    }

    public void setSelected(TextView textView, boolean selected) {
        if (selected) {
            textView.setBackgroundResource(R.drawable.orange_kong_bg);
            textView.setTextColor(activity.getResources().getColor(R.color.colordorange));
        } else {
            textView.setBackgroundResource(R.drawable.kong_bg);
            textView.setTextColor(activity.getResources().getColor(R.color.color333));
        }
    }

    class MultiItemViewHolder extends RecyclerView.ViewHolder {

        ItemShaixuangridV2Binding viewBinding;

        public MultiItemViewHolder(@NonNull View itemView) {
            super(itemView);
            viewBinding = ItemShaixuangridV2Binding.bind(itemView);
        }

        public void setItem(MultiItem o, ShaixuanallBean.DataBean dataBean) {
            viewBinding.recyclerView.setLayoutManager(new GridLayoutManager(itemView.getContext(), 2));
            viewBinding.recyclerView.setAdapter(new RecyclerView.Adapter() {
                @NonNull
                @Override
                public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                    return new TagViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_shuaixuanitem, parent, false));
                }

                @Override
                public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
                    TagViewHolder tagViewHolder = (TagViewHolder) holder;
                    ShaixuanallBean.DataBean.AttrListBean.AttrList2Bean item = o.multi.get(position);
                    tagViewHolder.viewBinding.tvName.setText(item.getAttr_value());
                    if (o.item.getSelected().contains(item)) {
                        setSelected(tagViewHolder.viewBinding.tvName, true);
                    } else {
                        setSelected(tagViewHolder.viewBinding.tvName, false);
                    }
                    tagViewHolder.viewBinding.getRoot().setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (o.item != null) {
                                if (o.item.getSelected().contains(item)) {
                                    o.item.getSelected().remove(item);
                                } else {
                                    o.item.getSelected().add(item);
                                }
                            }
                            notifyDataSetChanged();
                        }
                    });
                }

                @Override
                public int getItemCount() {
                    if (o.multi == null) {
                        return 0;
                    }
                    return o.multi.size();
                }
            });
        }
    }

    /**
     * 竖着的列表中的每一行的 标签布局列表
     */
    class TagAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
        List<Object> list = new ArrayList<>();
        ShaixuanallBean.DataBean dataBean;

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
            if (viewType == 1) {
                return new MultiItemViewHolder(layoutInflater.inflate(R.layout.item_shaixuangrid_v2, parent, false));
            }
            return new TagViewHolder(layoutInflater.inflate(R.layout.item_shuaixuanitem, parent, false));
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
            Object o = list.get(position);
            if (o instanceof ShaixuanallBean.DataBean.AttrListBean) {
                TagViewHolder holder1 = (TagViewHolder) holder;
                ShaixuanallBean.DataBean.AttrListBean item = (ShaixuanallBean.DataBean.AttrListBean) o;
                holder1.setData(dataBean, item);
                holder1.viewBinding.getRoot().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (dataBean != null) {
                            if (dataBean.getSelected().contains(item)) {
                                dataBean.getSelected().remove(item);
                            } else {
                                dataBean.getSelected().add(item);
                            }
                        }
                        if (!item.getAttr_list2().isEmpty()) {
                            boolean expand = item.isExpand();
                            if (expand) {
                                for (int i = 0; i < list.size(); i++) {
                                    Object o = list.get(i);
                                    if (o instanceof MultiItem) {
                                        list.remove(i);
                                        break;
                                    }
                                }
                            } else {
                                MultiItem multiItem = new MultiItem();
                                multiItem.multi = item.getAttr_list2();
                                multiItem.item = item;
                                int p = position;
                                if (position % 2 == 1) {
                                    p = position + 1;
                                } else {
                                    p = position + 2;
                                }
                                p = Math.min(p, list.size());
                                list.add(p, multiItem);
                            }
                            item.setExpand(!item.isExpand());
                            setList(dataBean, new ArrayList<>(list));
                        }
                        notifyDataSetChanged();
                    }
                });
            } else if (o instanceof Custom) {
                TagViewHolder holder1 = (TagViewHolder) holder;
                Custom custom = (Custom) o;
                if (TextUtils.isEmpty(custom.value)) {
                    setSelected(holder1.viewBinding.tvName, false);
                    holder1.viewBinding.tvName.setText(R.string.custom);
                } else {
                    holder1.viewBinding.tvName.setText(custom.value);
                    setSelected(holder1.viewBinding.tvName, true);
                }
                holder1.viewBinding.getRoot().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        InputCustomDialog dialog = new InputCustomDialog(activity);
                        dialog.setListener(new InputCustomDialog.InputListener() {
                            @Override
                            public void input(String str) {
                                custom.value = str;
                                notifyDataSetChanged();
                            }
                        });
                        dialog.show();
                    }
                });
            } else if (o instanceof MultiItem) {
                MultiItemViewHolder holder1 = (MultiItemViewHolder) holder;
                holder1.setItem((MultiItem) o, dataBean);
            }

        }

        @Override
        public int getItemCount() {
            return list.size();
        }

        @Override
        public int getItemViewType(int position) {
            Object o = list.get(position);
            if (o instanceof MultiItem) {
                return 1;
            }
            return 0;
        }

        public void setList(ShaixuanallBean.DataBean item, List<Object> attr_list) {
            dataBean = item;
            list = attr_list;
            notifyDataSetChanged();
        }
    }


    class TagViewHolder extends RecyclerView.ViewHolder {
        ItemShuaixuanitemBinding viewBinding;

        public TagViewHolder(@NonNull View itemView) {
            super(itemView);
            viewBinding = ItemShuaixuanitemBinding.bind(itemView);
        }

        public void setData(ShaixuanallBean.DataBean dataBean, ShaixuanallBean.DataBean.AttrListBean item) {
            viewBinding.tvName.setText(item.getAttr_value());
            if (dataBean != null) {
                if (dataBean.getSelected().contains(item)) {
                    setSelected(viewBinding.tvName, true);
                } else {
                    setSelected(viewBinding.tvName, false);
                }
            }

        }
    }

    class DataViewHolder extends RecyclerView.ViewHolder {

        ItemShaixuanallV2Binding viewBinding;
        private List<Object> list = new ArrayList<>();
        private TagAdapter tagAdapter = new TagAdapter();

        public DataViewHolder(@NonNull View itemView) {
            super(itemView);
            viewBinding = ItemShaixuanallV2Binding.bind(itemView);
            GridLayoutManager layoutManager = new GridLayoutManager(itemView.getContext(), 2);
            layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                @Override
                public int getSpanSize(int position) {
                    Object o = list.get(position);
                    if (o instanceof MultiItem) {
                        return 2;
                    }
                    return 1;
                }
            });
            viewBinding.recyclerView.setLayoutManager(layoutManager);
            viewBinding.recyclerView.setAdapter(tagAdapter);
        }

        public void setData(ShaixuanallBean.DataBean item) {
            viewBinding.tvName.setText(item.getAttr_name());
            list.clear();
            list.addAll(item.getAttr_list());
            if (IDS.contains(item.getId())) {
                Custom custom = new Custom();
                list.add(custom);
                item.setCustom(custom);
            }
            tagAdapter.setList(item, list);
        }
    }

    /**
     * 最外层，竖着的 列表
     */
    class DataAdapter extends RecyclerView.Adapter<DataViewHolder> {

        @NonNull
        @Override
        public DataViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = activity.getLayoutInflater().inflate(R.layout.item_shaixuanall_v2, parent, false);
            return new DataViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull DataViewHolder holder, int position) {
            ShaixuanallBean.DataBean item = totalData.get(position);
            holder.setData(item);
        }

        @Override
        public int getItemCount() {
            return totalData.size();
        }
    }

    public static class Custom {
        String value;
    }


    public static class MultiItem {
        public ShaixuanallBean.DataBean.AttrListBean item;
        List<ShaixuanallBean.DataBean.AttrListBean.AttrList2Bean> multi;
    }
}
